USE [Training]
GO

IF NOT EXISTS (SELECT * from dbo.sysobjects WHERE id = OBJECT_ID(N'dbo.training_api_DepartmentTreeSelectByChild'))
	EXEC('CREATE PROC dbo.training_api_DepartmentTreeSelectByChild AS')
GO

ALTER PROC dbo.training_api_DepartmentTreeSelectByChild
	@ChildID	int
AS
	SELECT
		dt.DepartmentTreeID,
		dt.LocationID,
		loc.Title [Location],
		p.DepartmentID [ParentId],
		p.Title [Parent],
		c.DepartmentID [ChildId],
		c.Title [Child]
	FROM 
		DepartmentTree dt JOIN
		Department p ON dt.Parent = p.DepartmentID JOIN
		Department c ON dt.Child = c.DepartmentID JOIN
		Location loc ON dt.LocationID = loc.LocationID		
	WHERE
		dt.Child = @ChildID
